//
//  WmcTeamMemberQRCodeInviteVM.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/14.
//

import Foundation
import RxRelay
import UIKit

class WmcTeamMemberQRCodeInviteVM: WmcBaseVM {
    var teamAblum: WmcMediaTeamAlbumModel?

    let inviationInfo: BehaviorRelay<WmcInviationInfoModel?> = .init(value: nil)

    /// 获取邀请相关的信息
    /// - Returns: description
    func getQrcode() {
        guard let teamId = teamAblum?.teamId else { return }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.getTeamInviationInfo(teamId: teamId).subscribe { [weak self] info in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            weakSelf.inviationInfo.accept(info)
        } onError: { error in
            WmcHudManager.toast(error)
            WmcHudManager.dismiss()
        }.disposed(by: rx.disposeBag)
    }

    /// 保存图片到本地相册
    /// - Parameter img: img description
    /// - Returns: description
    func saveImgToLocalAlbum(img: UIImage?) {
        // 相册权限判断
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            guard let img = img else {
                return
            }
            // 保存图片到本地相册
            UIImageWriteToSavedPhotosAlbum(img, self, #selector(saveImage(_:didFinishSaving:contextInfo:)), nil)
        } else {
            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
        }
    }

    /// 分享二维码图片给好友
    /// - Parameter img: img description
    /// - Returns: description
    func shareQrcodeToWechat(img: UIImage?) {
        guard let img = img else {
            return
        }
        let shareAlertView = WmcShareAlertView()
        let sharedConfig: WmcShareAlertView.ShareType.Config = .init(title: "",
                                                                     description: "",
                                                                     thumbImage: UIImage.YP.AppIcon)
        shareAlertView.shareType = .image(img, config: sharedConfig)
        let height = Wmc_safeAreaBottom + 214
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(height)
        }))
        presentVC.show()
    }
}

extension WmcTeamMemberQRCodeInviteVM {
    /// 保存图片到本地相册
    /// - Parameters:
    ///   - image: image description
    ///   - error: error description
    ///   - contextInfo: contextInfo description
    @objc private func saveImage(_: UIImage, didFinishSaving error: Error?, contextInfo _: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("保存成功")
        }
    }
}
